#!/bin/bash

# API连接问题修复脚本

echo "===== 开始修复API连接问题 ====="

# 1. 重启服务
echo "1. 重启容器服务..."
docker compose restart nginx measurement

# 2. 清除缓存
echo "2. 清除nginx缓存..."
docker compose exec nginx sh -c "rm -rf /var/cache/nginx/*" || true

# 3. 验证nginx配置
echo "3. 验证nginx配置..."
docker compose exec nginx nginx -t

# 4. 检查API路由是否正确
echo "4. 测试API路由..."
curl -v -X OPTIONS -H "Origin: https://mingyun.online" \
     -H "Access-Control-Request-Method: POST" \
     -H "Access-Control-Request-Headers: Content-Type" \
     https://mingyun.online/api/v1/register 2>&1 | grep -E "(< HTTP|Access-Control)"

echo ""
echo "如果上面显示了'HTTP/1.1 204 No Content'和Access-Control相关headers，则预检请求成功"

# 5. 查看服务日志中的错误
echo ""
echo "5. 查看nginx错误日志..."
docker compose exec nginx tail -n 20 /var/log/nginx/error.log

# 6. 添加测试请求
echo ""
echo "6. 发送测试注册请求..."
curl -v -X POST \
     -H "Content-Type: application/json" \
     -H "Origin: https://mingyun.online" \
     -d '{"username":"testuser123","password":"Test123456"}' \
     https://mingyun.online/api/v1/register

echo ""
echo "===== 修复完成 ====="
echo ""
echo "如果问题仍然存在，请尝试以下步骤:"
echo "1. 检查浏览器控制台中的具体错误信息"
echo "2. 尝试更改前端请求方式或内容类型"
echo "3. 查看后端日志检查是否有异常: docker compose logs --tail=100 measurement"
echo "4. 如果还有问题，请考虑重新启动整个服务: docker compose down && docker compose up -d" 